package com.baibei.ebec.welcome;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.SparseArray;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.crossboarder.R;
import com.baibei.ebec.quotation.AppQuotationFilter;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.IQuotationEvent;
import com.baibei.ebec.quotation.event.ITradeEvent;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IProductApi;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.model.CouponInfo;
import com.baibei.model.HomeIndexInfo;
import com.baibei.model.HomeIndexProductInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.TradeParams;
import com.baibei.model.TradeType;
import com.baibei.model.TradeWebSocketInfo;
import com.baibei.module.AppRouter;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.Empty;
import com.baibei.sdk.RxObservable;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.rae.swift.Rx;
import com.rae.widget.dialog.IAppDialog;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;

@Route(path = AppRouter.ROUTE_FIRST_BUY)
public class FirstBuyGuideActivity extends AppCompatActivity implements IQuotationEvent,ITradeEvent {

    @BindView(R.id.iv_product)
    ImageView ivProduct;
    @BindView(R.id.tv_product_name)
    TextView tvProductName;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_last_price)
    TextView tvLastPrice;
    @BindView(R.id.btn_buy)
    TextView btnBuy;
    @BindView(R.id.btn_sell)
    TextView btnSell;
    @BindView(R.id.btn_buy_now)
    TextView btnBuyNow;
    private IProductApi mProductApi;
    private CountDownTimer mCountDownTimer;
    private ArrayList<ProductInfo> productInfos;
    private int productId;
    private ProductInfo pInfo;
    private boolean isCanBuy;
    private TradeType type;
    private ITradeApi mTradeApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_buy_guide);
        ButterKnife.bind(this);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.width = (int) (display.getWidth() * 0.9);
        getWindow().setAttributes(attributes);
        setFinishOnTouchOutside(false);
        QuotationFilter filter = new QuotationFilter(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        filter.addAction(AppQuotationFilter.ACTION_TRADE_CREATED);
        QuotationManager.getInstance().register(this, filter);

        // webSocket 超时
        mCountDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                tradeFailed("订购超时，请重试");
            }
        };

        initView();
    }

    private void initView() {

        String strBuy = "<b>现价订货</b><br><small>价格上涨就赚</small>";
        btnBuy.setText(Html.fromHtml(strBuy));
        String strSell = "<b>结算价订货</b><br><small>价格下跌就赚</small>";
        btnSell.setText(Html.fromHtml(strSell));

        mProductApi = ApiFactory.getInstance().getProductApi();
        mTradeApi = ApiFactory.getInstance().getTradeApi();

        //获取数据并展示
        RxObservable.create(mProductApi.getHomeIndexInfos(), this.toString()).subscribe(new ApiDefaultObserver<HomeIndexInfo>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(HomeIndexInfo homeIndexInfo) {
                List<HomeIndexProductInfo> indexDetailDtoList = homeIndexInfo.getIndexDetailDtoList();
                productInfos = new ArrayList<>();
                for (int i = 0; i < indexDetailDtoList.size(); i++) {
                    List<ProductInfo> child = indexDetailDtoList.get(i).getChild();
                    for (int j = 0; j < child.size(); j++) {
                        productInfos.add(child.get(j));
                    }
                }
                dataHandle();
            }
        });
    }

    private void dataHandle() {
        for (ProductInfo productInfo : productInfos) {
            if (productInfo.getPrice() == 8.8) {
                pInfo = productInfo;
                productId = Rx.parseInt(productInfo.getProductId());
                Glide.with(this).load(productInfo.getProductPic()).into(ivProduct);
                tvProductName.setText(productInfo.getName());
                tvPrice.setText("¥" + productInfo.getPrice() + "元/件");
            }
        }
    }

    @OnClick(R.id.iv_close)
    public void onFinishClicked() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        QuotationManager.getInstance().unregister(this);
    }

    @Subscribe
    @Override
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        if (productId == 0) return;
        tvLastPrice.setText("¥" + quotations.get(productId).getLast());
    }

    @OnClick(R.id.tv_chart)
    public void onChartClicked() {
        PriceFlowDialog dialog = PriceFlowDialog.getInstance(pInfo);
        dialog.show(getSupportFragmentManager(), this.toString());
    }

    @OnClick(R.id.btn_buy)
    public void onBuyClicked() {
        btnBuy.setBackgroundResource(R.drawable.shape_textview_buy_chosen);
        btnSell.setBackgroundResource(R.drawable.shape_textview_sell);
        btnBuyNow.setBackgroundResource(R.drawable.shape_textview_buynow);
        btnBuyNow.setTextColor(getResources().getColor(R.color.white));
        isCanBuy = true;
        type = TradeType.BUY;
    }

    @OnClick(R.id.btn_sell)
    public void onSellClicked() {
        btnSell.setBackgroundResource(R.drawable.shape_textview_sell_chosen);
        btnBuy.setBackgroundResource(R.drawable.shape_textview_buy);
        btnBuyNow.setBackgroundResource(R.drawable.shape_textview_buynow);
        btnBuyNow.setTextColor(getResources().getColor(R.color.white));
        isCanBuy = true;
        type = TradeType.SELL;
    }

    @OnClick(R.id.btn_buy_now)
    public void onBuyNowClicked() {
        if (!isCanBuy) return;
        IAppDialog dialog = AppUI.loading(this, "订货中，请稍后..", 0.6f);
        dialog.setCanceledOnTouchOutside(false);
        getCouponInfo();
    }

    private void getCouponInfo() {
        RxObservable.create(mTradeApi.getValidCouponList(productId+""),this.toString()).subscribe(new ApiDefaultObserver<List<CouponInfo>>() {
            @Override
            protected void onError(String s) {
                tradeFailed("获取券信息失败，请重试");
            }

            @Override
            protected void accept(List<CouponInfo> couponInfos) {
                for (CouponInfo couponInfo : couponInfos){
                    if (couponInfo.getFaceValue() == 1){
                        trade(couponInfo);
                    }
                }
            }
        });
    }

    private void trade(CouponInfo couponInfo) {
        TradeParams params = new TradeParams();
        params.type = type;
        params.quantity = 1;
        params.amount = 8.8;
        params.fee = 0.8;
        params.upPercent = 0;
        params.downPercent = 0;
        params.couponInfo = couponInfo;

        Observable<Empty> observable;
        if (params.type == TradeType.BUY){
            observable = perforBuy(params,pInfo);
        } else {
            observable =perforSell(params,pInfo);
        }
        observable.subscribe(new ApiDefaultObserver<Empty>() {
            @Override
            protected void onError(String s) {
                tradeFailed("订货失败，"+s);
            }

            @Override
            protected void accept(Empty empty) {
                mCountDownTimer.cancel();
                mCountDownTimer.start(); // 等待消息推送过来
            }
        });
    }

    private Observable<Empty> perforBuy(TradeParams params, ProductInfo pInfo) {
        return RxObservable.create(mTradeApi.buy(pInfo.getProductId(), pInfo.getArea(), params.quantity, params.amount,params.fee,params.upPercent, params.downPercent, 1, params.couponInfo.getCouponId(),params.couponInfo.getCouponType()),this.toString());
    }

    private Observable<Empty> perforSell(TradeParams params, ProductInfo pInfo) {
        return RxObservable.create(mTradeApi.sell(pInfo.getProductId(), pInfo.getArea(), params.quantity, params.amount,params.fee,params.upPercent, params.downPercent, 1, params.couponInfo.getCouponId(),params.couponInfo.getCouponType()),this.toString());
    }

    @Subscribe
    @Override
    public void onEvent(TradeWebSocketInfo tradeInfo) {
        LogUtils.e("订购websocket推送to：" + tradeInfo);
        mCountDownTimer.cancel();
        if ("CODE_CREATE_SUCCESS".equalsIgnoreCase(tradeInfo.getCode())) {
            AppUI.dismiss();
            AppUI.success(this,"订货成功");
            AppRouter.routeToOrderCenter(this);
            finish();
        }
        if ("CODE_CREATE_FAIL".equalsIgnoreCase(tradeInfo.getCode())) {
            tradeFailed("订货失败，"+tradeInfo.getMsg());
        }
    }

    public void tradeFailed(String msg){
        AppUI.dismiss();
        AppUI.failed(this,msg);
    };
}
